const database = require("../app/database");

class Messageservices {
  //获取所有留言
  async getallmessage() {
    const str1 = `
      select *,
        (select JSON_OBJECT('username',username,'id',user.id,'avatar',user.avatar) from user where id=ma.user_id) author,
        (select count(*) from messagethumb mab where mab.message_id=ma.id) thumbcount 
      from message ma where messageid is null order by ma.createAt desc;
		`;
    const str2 = `
      select *,
        (select JSON_OBJECT('username',username,'id',user.id,'avatar',user.avatar) from user where id=ma.user_id) author,
        (select count(*) from messagethumb mab where mab.message_id=ma.id) thumbcount 
      from message ma where messageid=? order by ma.createAt desc;
    `;
    const [result] = await database.execute(str1);
    //递归查询
    const step = async (re, arr, replyname) => {
      const [r1] = await database.execute(str2, [re.id]);
      for (let i = 0; i < r1.length; i++) {
        arr.push({ ...r1[i], replyname });
        await step(r1[i], arr, r1[i].author.username);
      }
    };
    //查询每个评论下的评论
    for (let i = 0; i < result.length; i++) {
      const arr = [];
      await step(result[i], arr, result[i].author.username);
      result[i].childmessage = arr.slice();
    }
    return {
      result: 200,
      result,
    };
  }
  //回复留言
  async reply(body) {
    const { user_id, content, message_id } = body;
    const str = `
      insert into message(user_id,messageid,content) values(?,?,?)
    `;
    await database.execute(str, [
      user_id,
      message_id === -1 ? null : message_id,
      content,
    ]);
    return {
      status: 200,
      result: {
        message: "留言成功",
      },
    };
  }
  //删除留言
  async deletereply(id) {
    const str = `
      delete from message where id=?
    `;
    await database.execute(str, [id]);
    return {
      status: 200,
      result: {
        message: "删除评论成功",
      },
    };
  }
  //点赞或取消点赞
  async changethumb(body) {
    const { user_id, message_id } = body;
    const str1 = `
      select * from messagethumb where message_id=? and user_id=?
    `;
    const [re1] = await database.execute(str1, [message_id, user_id]);
    if (re1.length > 0) {
      const str2 = `
        delete from messagethumb where message_id=? and user_id=?
      `;
      await database.execute(str2, [message_id, user_id]);
    } else {
      const str2 = `
        insert into messagethumb(message_id,user_id) values(?,?)
      `;
      await database.execute(str2, [message_id, user_id]);
    }
    return {
      status: 200,
      result: {
        message: "操作成功",
      },
    };
  }

  //管理员获取所有评论
  async mangetallmessage() {
    const str = `
      select *,(select username from user where me.user_id=user.id) author from message me
    `;
    const [result] = await database.execute(str);
    return {
      status: 200,
      result,
    };
  }
}

module.exports = new Messageservices();
